package cn.itcast.itcaststore.dao.Impl;

import cn.itcast.itcaststore.dao.ProductDao;
import cn.itcast.itcaststore.domain.Products;
import cn.itcast.itcaststore.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class IProductDao implements ProductDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    public List getListProduct(String category, int currentPage, int orderByDate) {
        if ("全部商品".equals(category)){
            category="";
        }
        currentPage=(currentPage-1)*orderByDate;
//        不能使用加密只能拼接
        String getListProuct_sql = "select*from products where category like '%"+category+"%'limit "+currentPage+","+orderByDate;
//        String getListProuct_sql = "select*from products where category like %?% limit ?,?";
        List<Products> listProduct = jdbcTemplate.query(getListProuct_sql, new BeanPropertyRowMapper<Products>(Products.class));


        return listProduct;
    }

    @Override
    public Products getProducts(String id) {
        String getProduct_sql = "select*from products where id=?";
        List<Products> list = jdbcTemplate.query(getProduct_sql, new BeanPropertyRowMapper<Products>(Products.class), id);
        Products products=null;
        for (Products p : list) {
            products=p;
        }
        return products;
    }

    @Override
    public int getTotalDate(String category) {
        if ("全部商品".equals(category)){
            category="";
        }
        String getTotalDat_sql = "select count(category) from products where category like '%"+category+"%'";
        int total = jdbcTemplate.queryForObject(getTotalDat_sql, Integer.class);
        return total;
    }

    @Override
    public List getProductByname(String name, int currentPage, int orderByDate) {
        if ("请输入书名".equals(name)){
            name="";
        }
        currentPage=(currentPage-1)*orderByDate;
        String sql = "select*from products where name like '%"+name+"%'limit "+currentPage+","+orderByDate;
        List<Products> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Products>(Products.class));
        return query;
    }

    @Override
    public int getTotalDateByName(String name) {
        if ("请输入书名".equals(name)){
            name="";
        }
        String getTotalDat_sql = "select count(name) from products where name like '%"+name+"%'";
        int total = jdbcTemplate.queryForObject(getTotalDat_sql, Integer.class);
        return total;
    }

    @Override
    public Products getProductsById(String id) {
        String sql = "select*from products where id=?";
        List<Products> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Products>(Products.class), id);
        Products p=null;
        for (Products products : query) {
            p=products;
        }
        return p;
    }


}
